import axios from 'axios';
import qs from 'qs';
import global from './global';
import router from './router';

// axios 配置
axios.defaults.timeout = 60000;
axios.defaults.baseURL = global.API;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// http request 拦截器
axios.interceptors.request.use(
    (config) => {
      const token = localStorage.getItem('token');
      if (token) {
        config.headers.token = token;
      }
      const cabinetId = localStorage.getItem('cabinetId');
      if (cabinetId) {
        config.headers.cabinetId = cabinetId;
      }
      const contentType = config.headers['Content-Type'];
      if (typeof (contentType) === 'undefined') {
        config.transformRequest = [
          function(obj) {
            return qs.stringify(obj);
          }];
      }
      return config;
    },
    (err) => {
      return Promise.reject(err);
    },
);

// http response 拦截器
axios.interceptors.response.use(
    (response) => {
      const contentType = response.headers['content-type'];
      // console.log('response403', contentType);
      if (typeof (contentType) !== 'undefined' &&
          contentType.indexOf('application/json') > -1) {
      } else if (typeof (contentType) !== 'undefined' &&
          contentType.indexOf('text/html') > -1) {
        // console.log('response.data', response.data);
        if (typeof (response.data) !== 'undefined' &&
            response.data.indexOf('<title>403')) {
        }
      }
      return response;
    },
    (error) => {
      if (error.response) {
        switch (error.response.status) {
          case 401:
            router.push({ path: '/login' });
            break;
          case 500:
            router.push({ path: '' });
            break;
          default:
            router.push({ path: '' });
        }
      }
      // console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
      return Promise.reject(error.response.data);
    },
);

export default axios;
